package com.amazon.shop.controller;


import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.Orders;
import com.amazon.shop.entity.SalesmanInfo;
import com.amazon.shop.entity.SellerInfo;
import com.amazon.shop.entity.auth.*;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.*;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.vo.SalesmanInfoVo;
import com.amazon.shop.vo.Wage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-07-01
 */
@RestController
@RequestMapping("/shop/salesman-info")
@Api(tags = "业务员模块")
public class SalesmanInfoController {
    @Resource
    private SalesmanInfoService salesmanInfoService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private RolesService rolesService;
    @Resource
    private UsersRolesService usersRolesService;
    @Resource
    private RolesPermissionsService rolesPermissionsService;
    @Resource
    private OrderSimpleService orderSimpleService;
    @Resource
    private SellerInfoService sellerInfoService;

    /**
     * 新增业务员信息
     *
     * @param salesmanInfoVo
     * @param token
     * @return
     */
    @SystemLog(value = "新增业务员信息")
    @PostMapping("/saveSalesman")
    @ApiOperation(value = "新增业务员信息")
    @Transactional
    public CommonResult saveSalesman(@RequestBody SalesmanInfoVo salesmanInfoVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "1");
        if (flag) {
            SalesmanInfo salesmanInfo = new SalesmanInfo();

            //盐值加密密码存储
            String loginPassword = salesmanInfoVo.getLoginPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodePassword = encoder.encode(loginPassword);

            //属性对拷
            BeanUtils.copyProperties(salesmanInfoVo, salesmanInfo);

            //获取登录信息
            String number = salesmanInfoVo.getNumber();
            String loginName = salesmanInfoVo.getLoginName();
            String name = salesmanInfoVo.getName();
            String mail = salesmanInfoVo.getEmail();
            String qq = salesmanInfoVo.getQq();
            String phone = salesmanInfoVo.getPhone();
            //处理登录信息
            Users users = new Users();
            users.setUserId(number);
            users.setRealName(name);
            users.setPhone(phone);
            users.setEmail(mail);
            users.setQq(qq);
            users.setPassword(encodePassword);
            users.setUserName(loginName);
            //保存登录信息
            usersService.save(users);

            //根据角色查询角色编号
            String role = salesmanInfoVo.getRole();
            String apartment = salesmanInfoVo.getApartment();

            //设置角色信息
            Roles roles = new Roles();
            roles.setApartmentName(apartment);
            roles.setRoleName(role);

            //自定义角色编号
            String roleId = UUID.randomUUID().toString().replace("-", "");
            roles.setRoleId(roleId);
            //保存角色信息
            rolesService.save(roles);

            //保存用户角色信息
            UsersRoles usersRoles = new UsersRoles();
            usersRoles.setRoleId(roleId);
            usersRoles.setUserId(number);
            usersRolesService.save(usersRoles);

            //将权限列表放入同一个列表中
            List<String> permissionList = new ArrayList<>();
            List<String> amazonPermissionList = salesmanInfoVo.getAmazonPermissionList();
            List<String> moneyPermissionList = salesmanInfoVo.getMoneyPermissionList();
            List<String> orderPermissionList = salesmanInfoVo.getOrderPermissionList();
            List<String> productPermissionList = salesmanInfoVo.getProductPermissionList();
            List<String> systemPermissionList = salesmanInfoVo.getSystemPermissionList();
            List<String> transferPermissionList = salesmanInfoVo.getTransferPermissionList();

            permissionList.addAll(amazonPermissionList);
            permissionList.addAll(moneyPermissionList);
            permissionList.addAll(orderPermissionList);
            permissionList.addAll(productPermissionList);
            permissionList.addAll(systemPermissionList);
            permissionList.addAll(transferPermissionList);

            //保存权限列表
            List<RolesPermissions> rolesPermissionsList = permissionList.stream().map((permission) -> {
                RolesPermissions rolesPermissions = new RolesPermissions();

                //根据权限名称查询权限编号
                QueryWrapper<Permissions> permissionsQueryWrapper = new QueryWrapper<>();
                permissionsQueryWrapper.eq("name", permission);
                Permissions permissions = permissionsService.getOne(permissionsQueryWrapper);
                String permissionId = permissions.getPermissionId();

                //设置角色权限信息
                rolesPermissions.setPermissionId(permissionId);
                rolesPermissions.setRoleId(roleId);

                //自定义角色权限编号
                String id = UUID.randomUUID().toString().replace("-", "");
                rolesPermissions.setId(id);
                return rolesPermissions;
            }).collect(Collectors.toList());
            //批量保存 角色权限信息

            rolesPermissionsService.saveBatch(rolesPermissionsList);

            //保存业务员信息
            salesmanInfoService.save(salesmanInfo);

            String userRealName = usersService.getUserRealName(token);
            return CommonResult.success()
                    .put("list", number)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 查询业务员信息列表
     *
     * @param token
     * @return
     */
    @GetMapping("/getSalesmanInfo")
    @ApiOperation(value = "查询业务员信息列表")
    public CommonResult getSalesmanInfo(String token) {
        boolean flag = permissionsService.getPermissionList(token, "1");
        if (flag) {
            List<SalesmanInfo> salesmanInfos = salesmanInfoService.list();
            List<SalesmanInfoVo> salesmanInfoVoList = salesmanInfos.stream().map((salesmanInfo) -> {
                SalesmanInfoVo salesmanInfoVo = new SalesmanInfoVo();
                BeanUtils.copyProperties(salesmanInfo, salesmanInfoVo);
                return salesmanInfoVo;
            }).collect(Collectors.toList());

            return CommonResult.success("查询业务员信息列表")
                    .put("salesmanInfoVoList", salesmanInfoVoList);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取业务员详情信息
     *
     * @param number
     * @param token
     * @return
     */
    @GetMapping("/getSalesmanDetail")
    @ApiOperation(value = "获取业务员详情信息")
    public CommonResult getSalesmanDetail(String number, String token) {
        boolean flag = permissionsService.getPermissionList(token, "1");
        if (flag) {
            //根据编号获取业务员信息
            SalesmanInfo salesmanInfo = salesmanInfoService.getById(number);

            //根据token获取用户信息
            QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
            usersQueryWrapper.eq("token", token);
            Users users = usersService.getOne(usersQueryWrapper);
            //属性对拷

            SalesmanInfoVo salesmanInfoVo = new SalesmanInfoVo();

            //属性对拷
            BeanUtils.copyProperties(users, salesmanInfoVo);
            BeanUtils.copyProperties(salesmanInfo, salesmanInfoVo);

            //设置用户信息
            String userName = users.getUserName();
            salesmanInfoVo.setLoginName(userName);

            //根据用户编号获取对应角色
            QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
            String userId = users.getUserId();
            usersRolesQueryWrapper.eq("user_id", userId);
            UsersRoles usersRoles = usersRolesService.getOne(usersRolesQueryWrapper);

            //根据角色编号查询角色权限列表
            String roleId = usersRoles.getRoleId();
            QueryWrapper<RolesPermissions> rolesPermissionsQueryWrapper = new QueryWrapper<>();
            rolesPermissionsQueryWrapper.eq("role_id", roleId);
            List<RolesPermissions> permissionsList = rolesPermissionsService.list(rolesPermissionsQueryWrapper);

            //根据角色编号查询角色信息
            Roles roles = rolesService.getById(roleId);

            //设置部门信息
            String apartmentName = roles.getApartmentName();
            salesmanInfoVo.setApartment(apartmentName);

            //设置角色信息
            String roleName = roles.getRoleName();
            salesmanInfoVo.setRole(roleName);

            //查询权限信息
            List<String> collect = permissionsList.stream().map((rolesPermissions) -> {
                String permissionId = rolesPermissions.getPermissionId();
                Permissions permissions = permissionsService.getById(permissionId);
                String name = permissions.getName();
                return name;
            }).collect(Collectors.toList());

            //系统权限列表
            List<String> systemPermissionList = new ArrayList<>();
            //订单权限列表
            List<String> orderPermissionList = new ArrayList<>();
            //产品权限列表
            List<String> productPermissionList = new ArrayList<>();
            //亚马逊权限列表
            List<String> amazonPermissionList = new ArrayList<>();
            //转运权限列表
            List<String> transferPermissionList = new ArrayList<>();
            //财务权限列表
            List<String> moneyPermissionList = new ArrayList<>();

            for (String permission : collect) {
                if ("看业务员".equals(permission) || "改业务员".equals(permission) || "查看公司".equals(permission)
                        || "修改公司".equals(permission) || "合作伙伴".equals(permission) || "关联公司".equals(permission)
                        || "远程管理".equals(permission) || "检查替换".equals(permission) || "云主机".equals(permission)) {
                    systemPermissionList.add(permission);
                }
                if ("编辑产品".equals(permission) || "价格库存".equals(permission) || "分类维护".equals(permission)
                        || "产品删除".equals(permission) || "产品代理".equals(permission) || "产品供应".equals(permission)
                        || "产品图片".equals(permission) || "产品导出".equals(permission) || "分销调价".equals(permission)
                        || "运费模板".equals(permission) || "侵权词".equals(permission) || "批量导入".equals(permission)
                        || "批量采集 ".equals(permission) || "标题模板".equals(permission)) {
                    productPermissionList.add(permission);
                }
                if ("允许查看亚马逊".equals(permission) || "账号授权".equals(permission) || "上传产品".equals(permission)
                        || "修改明细".equals(permission) || "价格调整".equals(permission) || "UPC编码".equals(permission)
                        || "更新价格".equals(permission)) {
                    amazonPermissionList.add(permission);
                }
                if ("查看订单".equals(permission) || "接收订单".equals(permission) || "添加采购".equals(permission)
                        || "添加运单".equals(permission) || "批量操作".equals(permission) || "成本退款".equals(permission)
                        || "利润总额".equals(permission) || "远程管理".equals(permission) || "转运订单".equals(permission)
                        || "分销订单".equals(permission) || "导出订单".equals(permission) || "真送货".equals(permission)
                        || "下单器 ".equals(permission) || "全部列表".equals(permission))
                    orderPermissionList.add(permission);
                if ("允许查看物流".equals(permission) || "物流授权".equals(permission) || "报关信息".equals(permission)
                        || "修改运单".equals(permission) || "全部列表".equals(permission)) {
                    transferPermissionList.add(permission);
                }
                if ("允许查看财务".equals(permission) || "显示余额".equals(permission) || "账单明细".equals(permission)
                        || "余额提现".equals(permission) || "银行账户".equals(permission) || "运单费用".equals(permission)) {
                    moneyPermissionList.add(permission);
                }
            }

            //设置权限列表
            salesmanInfoVo.setSystemPermissionList(systemPermissionList);
            salesmanInfoVo.setAmazonPermissionList(amazonPermissionList);
            salesmanInfoVo.setMoneyPermissionList(moneyPermissionList);
            salesmanInfoVo.setTransferPermissionList(transferPermissionList);
            salesmanInfoVo.setProductPermissionList(productPermissionList);
            salesmanInfoVo.setOrderPermissionList(orderPermissionList);

            return CommonResult.success("业务员详情信息查询成功").put("salesmanInfoVo", salesmanInfoVo);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取工资提成列表
     *
     * @param token
     * @return
     */
    @GetMapping("/getWageList")
    @ApiOperation(value = "获取工资提成列表")
    public CommonResult getWageList(String token) {
        boolean flag = permissionsService.getPermissionList(token, "55");
        if (flag) {
            //查询业务员列表
            List<SalesmanInfo> salesmanInfos = salesmanInfoService.list();

            List<Wage> wageList = salesmanInfos.stream().map((salesmanInfo) -> {
                Wage wage = new Wage();

                //根据业务员编号查询业务员信息
                String number = salesmanInfo.getNumber();
                Users users = usersService.getById(number);

                //设置业务员姓名
                String realName = users.getRealName();
                wage.setSalesman(realName);

                //设置提成信息
                QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
                ordersQueryWrapper.eq("salesman_id", number);
                List<Orders> ordersList = orderSimpleService.list(ordersQueryWrapper);
                BigDecimal bigDecimal = new BigDecimal("0.00");
                for (Orders orders : ordersList) {
                    //根据卖家编号查询卖家信息
                    String sellerId = orders.getSellerId();
                    SellerInfo sellerInfo = sellerInfoService.getById(sellerId);
                    BigDecimal money = sellerInfo.getMoney();
                    bigDecimal.add(money);
                }

                //根据业务员编号查询业务员角色信息
                QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
                usersRolesQueryWrapper.eq("user_id", number);
                UsersRoles usersRoles = usersRolesService.getOne(usersRolesQueryWrapper);

                //根据角色编号查询角色信息
                String roleId = usersRoles.getRoleId();
                Roles roles = rolesService.getById(roleId);

                //设置部门信息
                String apartmentName = roles.getApartmentName();
                wage.setCompany(apartmentName);

                //设置销售利润
                BigDecimal profitCommission = salesmanInfo.getProfitCommission();
                BigDecimal salesCommissions = bigDecimal.multiply(profitCommission);
                wage.setSalesCommissions(salesCommissions);

                //设置基础工资
                BigDecimal minWages = salesmanInfo.getMinWages();
                wage.setBasicSalary(minWages);

                //设置应付工资
                wage.setDealSalary(minWages.add(salesCommissions));

                return wage;
            }).collect(Collectors.toList());

            return CommonResult.success("查询工资提成列表成功").put("wageList", wageList);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }
}

